package com.example.android2019.ch5broadcast;

import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.android2019.R;

public class BroadcastActivity extends AppCompatActivity implements View.OnClickListener {
    EditText ed_phone;
    Button btn;
    MyReceiver myReceiver;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_broadcast);
        ed_phone = findViewById(R.id.broadcast_ed_phone);
        btn = findViewById(R.id.broadcast_btn);
        btn.setOnClickListener(this);
        myReceiver = new MyReceiver();

        /*动态权限*/
        String[] s = {"android.permission.PROCESS_OUTGOING_CALLS"};
        ActivityCompat.requestPermissions(BroadcastActivity.this, s, 1);


        /*获取传递的数据*/
        Intent intent = this.getIntent();
        String a = intent.getStringExtra("test");
        Toast.makeText(this, a, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View v) {
        String phone = ed_phone.getText().toString();
        SharedPreferences sp = getSharedPreferences("phone", MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("phone", phone);
        editor.commit();
        Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onResume() {

        super.onResume();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.NEW_OUTGOING_CALL");
        registerReceiver(myReceiver, intentFilter);
    }

    @Override
    public void onPause() {

        super.onPause();
        unregisterReceiver(myReceiver);
    }
}
